package tests;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

import java.sql.SQLException;
import java.util.List;

import mailsystem.Mailbox;
import mailsystem.persistance.MailsystemPersistance;
import mailsystem.persistance.database.MailBoxDB;

import org.junit.Before;
import org.junit.Test;

public class MailBoxDBTests {
	MailBoxDB boxes;
	MailsystemPersistance persistanceMock = mock(MailsystemPersistance.class);
	
	@Before
	public void doBefore()
	{
		boxes = new MailBoxDB(persistanceMock);
		boxes.changeToTestMode();
	}

	@Test
	public void testAddMailBoxEntity() throws SQLException {
		int before = boxes.listAll().size();
		Mailbox entity = new Mailbox(before + 1, null, null, null, persistanceMock);
		
		entity.setName("Test" + entity.getBoxId());
		entity.setGreeting("Hola test");
		entity.setPasscode("123");
		
		boxes.add(entity);
		
		int after = boxes.listAll().size();
		assertEquals(before + 1, after);
	}
	
	@Test
	public void getAllMailBoxTest() throws SQLException {
		int before = boxes.listAll().size();
		Mailbox entity = new Mailbox(before + 1, null, null, null, persistanceMock);
			
		entity.setName("Test" + entity.getBoxId());
		entity.setGreeting("Hola test");
		entity.setPasscode("123");
		
		boxes.add(entity);
		
		Mailbox expected = boxes.listAll().get(before);
		assertEquals(expected, entity);
	}
	
	@Test
	public void updateTheLastMailBoxTest() throws SQLException {
		List<Mailbox> list = boxes.listAll();
		Mailbox entity = list.get(list.size() - 1);
		String before = entity.getName();
		
		entity.setName(entity.getName() + "tested");
		
		boxes.update(entity);
		
		list = boxes.listAll();
		entity = list.get(list.size() - 1);
		assertEquals(before + "tested", entity.getName());
	}
	
	@Test
	public void deleteTheLastMailBoxTest() throws SQLException {
		List<Mailbox> list = boxes.listAll();
		Mailbox entity = list.get(list.size() - 1);
		int before = boxes.listAll().size();	
		
		boxes.delete(entity);
		
		list = boxes.listAll();
		int now = boxes.listAll().size();		
		assertEquals(before - 1, now);
	}
}
